<template>
	<div>
		<el-card class="!border-none" shadow="never">
			<el-page-header :content="pageTitle" @back="$router.back()" />
		</el-card>
		<el-card class="!border-none mt-4 mb-4" shadow="never">
			<el-alert type="warning" :title="tipsInfo" :closable="false" show-icon></el-alert>
		</el-card>
		<el-card class="mt-4 !border-none" shadow="never">
			<el-tabs v-model="activeTab" @tab-click="handleClick">
				<el-tab-pane v-for="item in tabsForm" :label="item.name" :name="item.type" :index="item.id"
					:key="item.id" lazy>
					<component :is="item.component" v-if="activeTab == item.type" />
				</el-tab-pane>
			</el-tabs>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="messageTemplateEdit">
import { ref, reactive, defineAsyncComponent, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { noticeDetail } from '/@/api/setting/notice';

const pageType = ref('add');

const pageTitle = computed(() => {
	return pageType.value == 'add' ? '添加消息' : '编辑消息';
});

const route = useRoute();

const tipsInfo = ref('');

const activeTab = ref('');

const tabsForm = reactive([]);

const tabsMap = [
	{
		id: 0,
		type: 'system',
		name: '系统通知',
		component: defineAsyncComponent(() => import('./edit/systemForm.vue')),
		tips: '用户可在系统消息内查看',
	},
	{
		id: 1,
		type: 'sms',
		name: '短信通知',
		component: defineAsyncComponent(() => import('./edit/smsForm.vue')),
		tips: '用户绑定手机号时发送',
	},
	{
		id: 2,
		type: 'mail',
		name: '邮件通知',
		component: defineAsyncComponent(() => import('./edit/mailForm.vue')),
		tips: '用户绑定邮箱时发送',
	},
	{
		id: 3,
		type: 'wechat',
		name: '微信模板消息',
		component: defineAsyncComponent(() => import('./edit/wechatForm.vue')),
		tips: '用户关联微信公众号时发送',
	},
	{
		id: 4,
		type: 'applet',
		name: '微信小程序订阅',
		component: defineAsyncComponent(() => import('./edit/appletForm.vue')),
		tips: '用户关联微信小程序时发送',
	},
];

const handleClick = (tab: any, event: Event) => {
	activeTab.value = tab.props.name;
	setTips(tab.index)
};

const setFormData = async (id: any) => {
	const data = await noticeDetail({
		id: id,
	});

	if (data) {
		tabsMap.forEach((tab, index) => {
			let key = 'is_' + tab.type;
			if (data[key] != null && data[key] != undefined && data[key] > 0) {
				if (!activeTab.value) {
					activeTab.value = tab.type;
					setTips(tab.id)
				}
				tabsForm.push(tab);
			}
		});
	}
};

const setTips = (id: any) => {
	tipsInfo.value = tabsMap[id].tips;
};

onMounted(() => {
	if (route.query.id) {
		pageType.value = 'edit';
		setFormData(route.query.id);
	} else {
		pageType.value = 'add';
	}
});
</script>
